<?php
/**
 * Created by PhpStorm.
 * User: g
 * Date: 2018/2/1
 * Time: 13:00
 */

namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;
use PHPExcel;
use PHPExcel_Writer_Excel5;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Fill;
use PHPExcel_Style_Border;

class Jxshtgl extends Commonwork
{
    public function zuofeichuli(){
        $request = Request::instance();$data = $request->post();
      //print_r($data);exit;
        $fid=7;$aid=$data["kid"];
        $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
        if($res["operateStatus"]=="success"){
           
            $up["id"]=$aid;
            $up["state"]=8;
            try{
              Db::table("jxs_hetong")->update($up);
            }catch (\Exception $e){
            
              return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            return json_encode(["msg"=>"","state"=>1]);
            
        }else{
            return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
        }
    }
    public function baocunchuli(){
         $request = Request::instance();$data = $request->post();
       // print_r($data);exit;
        $adddata["state"]=3;
        //经销商
        if($data["jxs"])
            $adddata["jxs"]=$data["jxs"];
        else
             return json_encode(["msg"=>"经销商必须选择","state"=>2]);
        //营业地址类型
        $adddata["yydzlx"]=$data["yydzlx"];
        //营业地址
        if($data["yydz_provice"])
            $adddata["yydz_provice"]=$data["yydz_provice"];
        else
            return json_encode(["msg"=>"经销商营业地址必须填写完整","state"=>2]);
        if($data["yydz_city"])
            $adddata["yydz_city"]=$data["yydz_city"];
        else
            return json_encode(["msg"=>"经销商营业地址必须填写完整","state"=>2]);
        if($data["yydz_county"])
            $adddata["yydz_county"]=$data["yydz_county"];
        else
            return json_encode(["msg"=>"经销商营业地址必须填写完整","state"=>2]);
        if(trim($data["yddz_xxdz"]))
            $adddata["yddz_xxdz"]=trim($data["yddz_xxdz"]);
        else
            return json_encode(["msg"=>"经销商营业地址必须填写完整","state"=>2]);
        //合同年份
        if(trim($data["htmc_nf"]))
            $adddata["htmc_nf"]=trim($data["htmc_nf"]);
        else
            return json_encode(["msg"=>"合同年份必须填写完整","state"=>2]);
        //合同编号
        $adddata["htbh"]=$data["htbh"];
        $jxstitle=Db::table("cg_jxs")->where(["id"=>$data["jxs"]])->value("title");
        $adddata["ht_mc"]=$jxstitle."-".$adddata["htmc_nf"]."年合同";
        $adddata["title"]=$jxstitle."-".$adddata["htmc_nf"]."年合同";
        //合同有效期
        if($data["htyxq_start"])
            $adddata["start"]=strtotime($data["htyxq_start"]);
        else
            return json_encode(["msg"=>"合同有效期必须填写完整","state"=>2]);
        if($data["htyxq_end"])
            $adddata["end"]=strtotime($data["htyxq_end"]);
        else
            return json_encode(["msg"=>"合同有效期必须填写完整","state"=>2]);
        //合同销售目标
        if($data["htxsmb"])
            $adddata["htxsmb"]=$data["htxsmb"];
        else
            return json_encode(["msg"=>"合同销售目标必须填写完整","state"=>2]);
        if($data["ysfymb"])
            $adddata["ysfymb"]=$data["ysfymb"];
        else
            return json_encode(["msg"=>"预算费用目标必须填写完整","state"=>2]);
        //目标费用率
        if($data["mbfyl"])
            $adddata["mbfyl"]=$data["mbfyl"];
        else
            return json_encode(["msg"=>"目标费用率必须填写完整","state"=>2]);
        //授权品牌
        if($data["sqpp"]){
            $adddata["sqpp"]=$data["sqpp"];
            $adddata["sqppstr"]=$data["sqppstr"];
        }else
            return json_encode(["msg"=>"授权品牌必须选择","state"=>2]);
        //授权品类
        if($data["sqpl"]){
            $adddata["sqpl"]=$data["sqpl"];
            $adddata["sqplstr"]=$data["sqplstr"];
        }else
            return json_encode(["msg"=>"授权品类必须选择","state"=>2]);
        //经销类型
        $adddata["jxlx"]=$data["jxlx"];
        if($data["jxlx"]==1){
            //区域经销
            if($data["sqqy"]){
                $adddata["sqqy"]=$data["sqqy"];
                $adddata["sqqystr"]=$data["sqqystr"];

            }else{
                return json_encode(["msg"=>"授权区域必须选择","state"=>2]);
            }
        }else{
            //系统经销
            if(trim($data["sqxt"]))
                $adddata["sqxt"]=$data["sqxt"];
            else
                return json_encode(["msg"=>"授权系统必须填写","state"=>2]);
        }
        //法人
        if(trim($data["cw_legalrepre"]))
            $adddata["cw_legalrepre"]=trim($data["cw_legalrepre"]);
        else
            return json_encode(["msg"=>"法定代表人必须填写","state"=>2]);
        $adddata["cw_lrphone"]=$data["cw_lrphone"];
        $adddata["cw_lrmobile"]=$data["cw_lrmobile"];
        $adddata["cw_lremail"]=$data["cw_lremail"];
        $adddata["cw_qualification"]=$data["cw_qualification"];
        if(trim($data["cw_taxsn"]))
            $adddata["cw_taxsn"]=trim($data["cw_taxsn"]);
        else
            return json_encode(["msg"=>"税号必须填写","state"=>2]);
        if(trim($data["cw_bank"]))
            $adddata["cw_bank"]=trim($data["cw_bank"]);
        else
            return json_encode(["msg"=>"开户行必须填写","state"=>2]);
        if(trim($data["cw_banksn"]))
            $adddata["cw_banksn"]=trim($data["cw_banksn"]);
        else
            return json_encode(["msg"=>"开户行帐号必须填写","state"=>2]);
        if(trim($data["cw_mailaddr"]))
            $adddata["cw_mailaddr"]=trim($data["cw_mailaddr"]);
        else
            return json_encode(["msg"=>"邮寄地址必须填写","state"=>2]);
        if(trim($data["cw_zipcode"]))
            $adddata["cw_zipcode"]=trim($data["cw_zipcode"]);
        else
            return json_encode(["msg"=>"邮寄地址邮编必须填写","state"=>2]);
        $adddata["cw_contact"]=$data["cw_contact"];
        $adddata["cw_phone"]=$data["cw_phone"];
        $adddata["cw_email"]=$data["cw_email"];
        //业务联系人
        if(trim($data["bs_contact"]))
            $adddata["bs_contact"]=trim($data["bs_contact"]);
        else
            return json_encode(["msg"=>"业务联系人必须填写","state"=>2]);
        if(trim($data["bs_phone"]))
            $adddata["bs_phone"]=trim($data["bs_phone"]);
        else
            return json_encode(["msg"=>"业务联系人电话必须填写","state"=>2]);
        if(trim($data["bs_mobile"]))
            $adddata["bs_mobile"]=trim($data["bs_mobile"]);
        else
            return json_encode(["msg"=>"业务联系人手机必须填写","state"=>2]);
        if(trim($data["bs_fax"]))
            $adddata["bs_fax"]=trim($data["bs_fax"]);
        else
            return json_encode(["msg"=>"业务联系人传真必须填写","state"=>2]);
        if(trim($data["bs_rcv_unit"]))
            $adddata["bs_rcv_unit"]=trim($data["bs_rcv_unit"]);
        else
            return json_encode(["msg"=>"收货单位必须填写","state"=>2]);
        if(trim($data["bs_rcv_addr"]))
            $adddata["bs_rcv_addr"]=trim($data["bs_rcv_addr"]);
        else
            return json_encode(["msg"=>"业务收货地址必须填写","state"=>2]);
        if(trim($data["bs_rcv_one"]))
            $adddata["bs_rcv_one"]=trim($data["bs_rcv_one"]);
        else
            return json_encode(["msg"=>"业务收货人必须填写","state"=>2]);
        if(trim($data["bs_rcv_phone"]))
            $adddata["bs_rcv_phone"]=trim($data["bs_rcv_phone"]);
        else
            return json_encode(["msg"=>"业务收货人电话必须填写","state"=>2]);
        //合同签署情况
        if($data["qstime"])
            $adddata["qstime"]=strtotime($data["qstime"]);
        else
            return json_encode(["msg"=>"合同签署日期必须填写","state"=>2]);
        if($data["wofanguser"])
            $adddata["wofanguser"]=$data["wofanguser"];
        else
            return json_encode(["msg"=>"我方签署人必须填写","state"=>2]);
        if(trim($data["df_ren"]))
            $adddata["df_ren"]=trim($data["df_ren"]);
        else
            return json_encode(["msg"=>"对方签署人必须填写","state"=>2]);
        if(trim($data["df_job"]))
            $adddata["df_job"]=trim($data["df_job"]);
        else
            return json_encode(["msg"=>"对方签署人职位必须填写","state"=>2]);
        if(trim($data["df_phone"]))
            $adddata["df_phone"]=trim($data["df_phone"]);
        else
            return json_encode(["msg"=>"对方签署人电话必须填写","state"=>2]);
        if(trim($data["df_email"]))
            $adddata["df_email"]=trim($data["df_email"]);
        else
            return json_encode(["msg"=>"对方签署人邮箱必须填写","state"=>2]);
        if(trim($data["df_addr"]))
            $adddata["df_addr"]=trim($data["df_addr"]);
        else
            return json_encode(["msg"=>"对方签署人地址必须填写","state"=>2]);
        //特殊合同
        $adddata["ts"]=$data["ts"];
        //特殊说明
        if($data["ts"]){
            if(trim($data["tsmiaoshu"]))
                $adddata["tsmiaoshu"]=trim($data["tsmiaoshu"]);
            else
                return json_encode(["msg"=>"特殊条款备注必须填写","state"=>2]);
        }
        if(trim($data["miaoshu"]))
            $adddata["miaoshu"]=trim($data["miaoshu"]);
        else
            return json_encode(["msg"=>"合同描述必须填写","state"=>2]);
        //附件
        $adddata["fujian"]=$data["attach"];
        //明细类型
        $adddata["detail_type"]=$data["mxtype"];
        //分解类型
        $typename="默认";
        switch ($adddata["detail_type"]) {
            case 2:
                # code...
                $typename="品牌";
                break;
            case 3:
                # code...
                $typename="品类";
                break;
            case 4:
                # code...
                $typename="系列";
                break;
        }
        //return json_encode(["msg"=>"完成","state"=>2]);
        //明细分解
        $mxdata["detail_type"]=$data["mxtype"];
        if($data["mxtype"]==1){
            $mxdata["prolist"]=[];
        }else{
            if(isset($data["prolist"])){
                for($i=0;$i<count($data["prolist"]);$i++){
                    if(trim($data["prolist"][$i]))
                        $data["prolist"][$i]=trim($data["prolist"][$i]);
                    else
                        return json_encode(["msg"=>"存在未填写名称的{$typename}","state"=>2]);
                }
                $mxdata["prolist"]=json_encode($data["prolist"]);
            }else{
                
                return json_encode(["msg"=>"目标分解中至少添加一个{$typename}","state"=>2]);
            }
        }
        //分解金额
        //print_r($data["sale_target"]);exit;
        if(isset($data["sale_target"])){
            $mxdata["sale_target"]=json_encode($data["sale_target"]);
        }else{
            return json_encode(["msg"=>"目标分解中至少存在一条明细","state"=>2]);
        }
        if(isset($data["yusuan_target"])){
            $mxdata["yusuan_target"]=json_encode($data["yusuan_target"]);
        }else{
            return json_encode(["msg"=>"目标分解中至少存在一条明细","state"=>2]);
        }

        if(isset($data["kaohe2"])){
            $mxdata["kaohe2"]=json_encode($data["kaohe2"]);
        }else{
            return json_encode(["msg"=>"目标分解中至少存在一条明细","state"=>2]);
        }
        //echo $mxdata["yusuan_target"];exit;
        if($data["kid"]){
            //修改
            $adddata["puser"]=Session::get("employee_id");
            $adddata["ptime"]=time();
            $adddata["id"]=$data["kid"];
            Db::startTrans();
            try{
                $res1=Db::table("jxs_hetong")->update($adddata);
                
                Db::table("jxs_hetong_fenjie")->where(["hid"=>$data["kid"]])->update($mxdata);
            }catch (\Exception $e) {
                Db::rollBack();
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            if($res1) {
                 $fid=7;$aid=$data["kid"];
                $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
                if($res["operateStatus"]=="success"){
                   Db::commit();
                    return json_encode(["msg"=>"","state"=>1]);
                    
                }else{
                    Db::rollBack();
                    return json_encode(["msg"=>"系统繁忙请稍后再试123","state"=>2]);
                }
            }else{
                 Db::rollBack();
                return json_encode(["msg"=>"系统繁忙请稍后再试321","state"=>2]);
            }
        }
    }
    public function zuofei($kid,$from=1){
        //查询营业地址所有的省份
      
        $this->assign("from",$from);
        $provices = db('cg_provice')->field('id,title')->select();
        $cities = db('cg_city')->field('id,title,provice as pid')->select();
        $counties = db('cg_county')->field('id,title,city as pid')->select();
        $this->assign([
            'provices'=>$provices,
            'cities' =>$cities,
            'counties' =>$counties,
        ]);
        if($kid){
            $apply=Db::table("jxs_hetong")->where(["id"=>$kid])->find();
            $apply["start"]=date("Y-m-d",$apply["start"]);
            $apply["end"]=date("Y-m-d",$apply["end"]);
            $apply["qstime"]=date("Y-m-d",$apply["qstime"]);
            $this->assign("apply",$apply);
            $jxs=Db::table("cg_jxs")->where("id={$apply["jxs"]}")->find();
        $jxs['cooptime'] = $this->DiffDate(date('Y-m-d',$jxs['cooptime']),date('Y-m-d'));
        $jxs['qudao']=Db::table("cg_channel_types1")->where("id={$jxs["channeltype"]}")->value("title");
        
        $this->assign("jxs",$jxs);
                 //查询合同提交人信息
            $eid=$apply["cuser"];

            $user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->where("em.id=$eid and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id")
            ->find();
            $today=date("Y-m-d",$apply["ctime"]);
            if($apply["fujian"])
                $fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
            else
                $fujian=[];
            //明细处理
            $mx=Db::table("jxs_hetong_fenjie")->where(["hid"=>$kid])->find();
            $lans=json_decode($mx["prolist"],true);
            $this->assign("lans",$lans);
            $xh=count($lans);
            $this->assign("xh",$xh);
            $mx["kaohe2"]=json_decode($mx["kaohe2"],true);
            $sale_target=json_decode($mx["sale_target"],true);
            $yusuan_target=json_decode($mx["yusuan_target"],true);
            $kaohe2str=implode(',',$mx["kaohe2"]);
            $kaohe2=Db::table("cg_cainian")->alias("c")
            ->join("cg_kaoheqi1 k1","k1.cid=c.id")
            ->join("cg_kaoheqi2 k2","k2.pid=k1.id")
            ->where("k2.id in ($kaohe2str)")
            ->field("c.title as cainian,c.id as cid,k2.title as yue,k2.id as k2id")
            ->select();
            //if()
            $this->assign("kaohe2",$kaohe2);
            $this->assign("sale_target",$sale_target);
            $this->assign("yusuan_target",$yusuan_target);
        }else{
               //查询合同提交人信息
            $eid=Session::get("employee_id");

            $user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->where("em.id=$eid and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id")
            ->find();
            $today=date("Y-m-d");

            $fujian=[];
        }
        $this->assign("kid",$kid);
        $this->assign("user",$user);
        $this->assign("fujian",$fujian);
        $this->assign("today",$today);
         $btn=$this->getbton(7,$kid);
        $this->assign("btn",$btn);
        $logs=$this->getlog(7,$kid);
        //print_r($logs);
        $this->assign("logs",$logs);
        return $this->fetch();
    }
    //审核
    public function shenhe($myId){
        $workfloawde=Db::table("cg_workflow")->where(["id"=>$myId])->find();
       // $aid=$workfloawde["yw_id"];
        $hid=$workfloawde["yw_id"];
        $ht=Db::table("jxs_hetong")->where("id=$hid")->find();
        if($ht["state"]==2){
            $this->redirect('Jxshtgl/zuofei', ['kid' => $hid,"from"=>2]);
        }else{
            if($ht["yydzlx"]==1)
                $ht["yydzlx"]="省级";
            else if($ht["yydzlx"]==2)
                $ht["yydzlx"]="市级";
            else
                $ht["yydzlx"]="县级";

            $ht["yydz_provice"]=Db::table("cg_provice")->where("id={$ht["yydz_provice"]}")->value("title");
            $ht["yydz_city"]=Db::table("cg_city")->where("id={$ht["yydz_city"]}")->value("title");
            $ht["yydz_county"]=Db::table("cg_county")->where("id={$ht["yydz_county"]}")->value("title");
            $ht["start"]=date("Y-m-d",$ht["start"]);$ht["end"]=date("Y-m-d",$ht["end"]);
            $ht["ctime"]=date("Y-m-d",$ht["ctime"]);$ht["qstime"]=date("Y-m-d",$ht["qstime"]);

            $ht["wofanguser"]=Db::table("employee")->where("id={$ht["wofanguser"]}")->value("em_name");
            $this->assign("ht",$ht);
             $fujian=[];
                //print_r($apply);
                if($ht["fujian"]){
                    $fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
                    //print_r($fujian);
                }
            $this->assign("fujian",$fujian);
            $jxs=Db::table("cg_jxs")->where("id={$ht["jxs"]}")->find();
            $jxs['cooptime'] = $this->DiffDate(date('Y-m-d',$jxs['cooptime']),date('Y-m-d'));
            $jxs['qudao']=Db::table("cg_channel_types1")->where("id={$jxs["channeltype"]}")->value("title");
            
            $this->assign("jxs",$jxs);

              $user=Db::table("employee")->alias("em")
                ->join("department_employee de","de.employee_id=em.id")
                ->join("department d","de.department_id=d.id")
                ->where("em.id={$ht["cuser"]} and de.index=1")
                ->field("em.em_name,d.de_name,em.mobile,em.id")
                ->find();
                $this->assign("user",$user);
            $htmx=Db::table("jxs_hetong_fenjie")->where("hid={$ht["id"]}")->find();
            $htmx["prolist"]=json_decode($htmx["prolist"],true);
            $htmx["kaohe2"]=json_decode($htmx["kaohe2"],true);
            $htmx["sale_target"]=json_decode($htmx["sale_target"],true);
            $htmx["yusuan_target"]=json_decode($htmx["yusuan_target"],true);
            $kaohe2str=implode(',',$htmx["kaohe2"]);
            $kaohe2=Db::table("cg_cainian")->alias("c")
            ->join("cg_kaoheqi1 k1","k1.cid=c.id")
            ->join("cg_kaoheqi2 k2","k2.pid=k1.id")
            ->where("k2.id in ($kaohe2str)")
            ->field("c.title as cainian,c.id as cid,k2.title as yue,k2.id as k2id")
            ->select();
            $this->assign("kaohe2",$kaohe2);
            $this->assign("htmx",$htmx);
             $logs=$this->getlog(7,$hid);
            //print_r($logs);
            $this->assign("logs",$logs);
            return $this->fetch();
        }

        
    }
    //详情
    public function detail($hid){
        $ht=Db::table("jxs_hetong")->where("id=$hid")->find();
        if($ht["yydzlx"]==1)
            $ht["yydzlx"]="省级";
        else if($ht["yydzlx"]==2)
            $ht["yydzlx"]="市级";
        else
            $ht["yydzlx"]="县级";

        $ht["yydz_provice"]=Db::table("cg_provice")->where("id={$ht["yydz_provice"]}")->value("title");
        $ht["yydz_city"]=Db::table("cg_city")->where("id={$ht["yydz_city"]}")->value("title");
        $ht["yydz_county"]=Db::table("cg_county")->where("id={$ht["yydz_county"]}")->value("title");
        $ht["start"]=date("Y-m-d",$ht["start"]);$ht["end"]=date("Y-m-d",$ht["end"]);
        $ht["ctime"]=date("Y-m-d",$ht["ctime"]);$ht["qstime"]=date("Y-m-d",$ht["qstime"]);

        $ht["wofanguser"]=Db::table("employee")->where("id={$ht["wofanguser"]}")->value("em_name");
        $this->assign("ht",$ht);
         $fujian=[];
            //print_r($apply);
            if($ht["fujian"]){
                $fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
                //print_r($fujian);
            }
        $this->assign("fujian",$fujian);
        $jxs=Db::table("cg_jxs")->where("id={$ht["jxs"]}")->find();
        $jxs['cooptime'] = $this->DiffDate(date('Y-m-d',$jxs['cooptime']),date('Y-m-d'));
        $jxs['qudao']=Db::table("cg_channel_types1")->where("id={$jxs["channeltype"]}")->value("title");
        
        $this->assign("jxs",$jxs);

          $user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->where("em.id={$ht["cuser"]} and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id")
            ->find();
            $this->assign("user",$user);
        $htmx=Db::table("jxs_hetong_fenjie")->where("hid={$ht["id"]}")->find();
        $htmx["prolist"]=json_decode($htmx["prolist"],true);
        $htmx["kaohe2"]=json_decode($htmx["kaohe2"],true);
        $htmx["sale_target"]=json_decode($htmx["sale_target"],true);
        $htmx["yusuan_target"]=json_decode($htmx["yusuan_target"],true);
        $kaohe2str=implode(',',$htmx["kaohe2"]);
        $kaohe2=Db::table("cg_cainian")->alias("c")
        ->join("cg_kaoheqi1 k1","k1.cid=c.id")
        ->join("cg_kaoheqi2 k2","k2.pid=k1.id")
        ->where("k2.id in ($kaohe2str)")
        ->field("c.title as cainian,c.id as cid,k2.title as yue,k2.id as k2id")
        ->select();
        $this->assign("kaohe2",$kaohe2);
        $this->assign("htmx",$htmx);
         $logs=$this->getlog(7,$hid);
        //print_r($logs);
        $this->assign("logs",$logs);
        return $this->fetch();
    }
    //绘制表格
    public function gettable(){
        $request = Request::instance();$data = $request->post();
       // print_r($data);exit;
       $start=strtotime($data["start"]);$end=strtotime($data["end"]);
         $time=Db::table("cg_cainian")->alias("c")
        ->join("cg_kaoheqi1 k1","k1.cid=c.id")
        ->join("cg_kaoheqi2 k2","k2.pid=k1.id")
        ->where("k2.starttime<=$end and k2.endtime>=$start")
        ->field("c.title as cainian,c.id as cid,k2.title as yue,k2.id as k2id")
        ->select();
        //print_r($time);exit;
        $where=["is_actived"=>1,"is_deleted"=>0];

        $list=[];
        switch($data["type"]){
            case 2:$list=Db::table("pro_brands")->where($where)->field("id,brand_name as title")->select();break;
            case 3:$list=Db::table("pro_category")->where($where)->field("id,category_name as title")->select();break;
            case 4:$list=Db::table("pro_series")->where($where)->field("id,series_name as title")->select();break;
            default:$list=[];break;
        }
        $res["lan"]=count($list);
        $trs="<table class='table-bordered' style='width:100%'><tr>";
        for($j=0;$j<count($list);$j++){
            $trs.="<td class='text-center' style='min-width:150px' xh='{$j}'><input type='hidden' name='prolist[]' value='{$list[$j]["title"]}'/>{$list[$j]["title"]}<br/><input type='button' value='删除' onclick='shanchuduiying({$j})'/></td>";
        }

        $trs.="<td class='text-center' style='min-width:150px'>小计</td></tr></table>";
        $trs2="<table class='table-bordered' style='width:100%'><tr>";
        for($j=0;$j<count($list);$j++){
            $trs2.="<td class='text-center' style='min-width:150px' xh='{$j}'>{$list[$j]["title"]}<br/><input type='button' value='删除' onclick='shanchuduiying({$j})'/></td>";
        }
        $trs2.="<td class='text-center' style='min-width:150px'>小计</td></tr></table>";
        $res["title1"]=$trs;
        $res["title2"]=$trs2;
        //
        $neirong1="<table class='table-bordered' style='width:100%'>";
        $neirong2="<table class='table-bordered' style='width:100%'>";
        $times="<table class='table-bordered' style='width:100%'>";

        for($i=0;$i<count($time);$i++){
            $neirong1.="<tr namez='sale_target[{$time[$i]["k2id"]}][]'>";
            $neirong2.="<tr namez='yusuan_target[{$time[$i]["k2id"]}][]'>";
            $times.="<tr><td class='text-center' style='min-width:100px'><input type='hidden' name='kaohe2[]' value='{$time[$i]["k2id"]}'/>{$time[$i]["cainian"]}年-{$time[$i]["yue"]}</td></tr>";
            for($j=0;$j<count($list);$j++){
                $neirong1.="<td style='min-width:150px' xh='{$j}'><input type='text' style='width:100px' class='form-control' name='sale_target[{$time[$i]["k2id"]}][]' onblur='xiaoshoujisuan()'/></td>";
                $neirong2.="<td style='min-width:150px' xh='{$j}'><input type='text' style='width:100px' class='form-control' name='yusuan_target[{$time[$i]["k2id"]}][]' onblur='yusuanjisuan()'/></td>";
            }
            if($data["type"]!=1){
                $neirong1.="<td style='min-width:150px'><input type='text' style='width:100px' class='form-control' name='sale_target[{$time[$i]["k2id"]}][]' readonly/></td></tr>";
                $neirong2.="<td style='min-width:150px'><input type='text' style='width:100px' class='form-control' name='yusuan_target[{$time[$i]["k2id"]}][]' readonly/></td></tr>";
            }else{
                $neirong1.="<td style='min-width:150px'><input type='text' style='width:300px' class='form-control xstar' onblur='morenxsjisuan()' name='sale_target[{$time[$i]["k2id"]}][]'/></td></tr>";
                $neirong2.="<td style='min-width:150px'><input type='text' style='width:300px' class='form-control ystar' onblur='morenysjisuan()' name='yusuan_target[{$time[$i]["k2id"]}][]'/></td></tr>";
            }
            
        }
        $neirong2.="</table>";
            $neirong1.="</table>";
            $times.="</table>";
        $res["neirong1"]=$neirong1;
        $res["neirong2"]=$neirong2;
        $res["times"]=$times;
        $res["xh"]=count($list)-1;
        return json_encode($res);

    }
    //获取完成区域
    public function getfullarea(){
        $request = Request::instance();$data = $request->post();
        //print_r($data);exit;
        $str=$data["txt"];
        $arr=json_decode($str,true);
        //print_r($arr);exit;
        $ids=[];
        if($arr){
            for($i=0;$i<count($arr);$i++){
                $ids[]=$arr[$i]["id"];
            }
        }
        $id=implode(',',$ids);

        $txts=[];
        if($id){
            $countys=Db::table("cg_county")->alias("c")->join("cg_city cc","c.city=cc.id")->join("cg_provice p","cc.provice=p.id")->where("c.id in ($id)")->field("c.title as qu,cc.title as shi,p.title as sheng")->select();
            for($i=0;$i<count($countys);$i++){
                $txts[]=$countys[$i]["sheng"]."-".$countys[$i]["shi"]."-".$countys[$i]["qu"];
            }
        }
        $txt=implode(' ; ',$txts);
        $res["id"]=$id;
        $res["txt"]=$txt;
        return json_encode($res);
        
    }
    //授权区域
    public function sqqy(){
        return $this->fetch();
    }

    //授权区域树
    public function sqqyTree(){
        $data = db('cg_provice')->field('id,title name')->select();
        foreach($data as $k=>$v){
            $city = db('cg_city')->where('provice',$v['id'])->field('id,title name')->select();
            foreach($city as $k1=>$v1){
                $v1['children'] = db('cg_county')->where('city',$v1['id'])->field('id,title name')->select();
                $city[$k1] = $v1;
            }
            $v['children'] = $city;
            $data[$k] = $v;
        }
       // print_r($data);exit;
        echo json_encode($data);
    }
    //删除
    public function shanchu($id){
        $res=Db::table("jxs_hetong")->where(["id"=>$id])->update(["is_deleted"=>1]);
        if($res)
            return 1;
        else
            return 2;
    }
    //提交工作流
    public function tijiao($id){
        $back=$this->gowork(7,$id);
        return $back;
    }
    //经销商合同管理
    public function index($page=1,$list=10){
        $request = Request::instance();$data = $request->post();
        $state=Db::table("ti_state")->order("paixu")->select();

        $this->assign("state",$state);
        $eid=Session::get("employee_id");
        $where="ht.is_deleted=0 and ht.cuser=$eid ";
        if($data){
            //签署时间
            if(trim($data["start"])){
                $start=strtotime(trim($data["start"]));
                $where.="and ht.qstime>=$start ";
            }
            if(trim($data["end"])){
                $end=strtotime(trim($data["end"]));
                $where.="and ht.qstime<=$end ";
            }
            //地区
            if(trim($data["fenqu"])){
                $fenqu=trim($data["fenqu"]);
                $tmp=Db::table("cg_market_zoning")->where(["title"=>$fenqu])->field("id")->find();
                if($tmp)
                    $fenqu=$tmp["id"];
                else
                    $fenqu=-1;
                $where.="and j.zoning=$fenqu ";
            }
            if(trim($data["sheng"])){
                $sheng=trim($data["sheng"]);
                $tmp=Db::table("cg_market_provice")->where(["title"=>$sheng])->field("id")->find();
                if($tmp)
                    $sheng=$tmp["id"];
                else
                    $sheng=-1;
                $where.="and j.provice=$fenqu ";
            }
            if(trim($data["shi"])){
                $shi=trim($data["shi"]);
                $tmp=Db::table("cg_market_city")->where(["title"=>$shi])->field("id")->find();
                if($tmp)
                    $shi=$tmp["id"];
                else
                    $shi=-1;
                $where.="and j.city=$fenqu ";
            }
            //合同费用率
            if(trim($data["feilvdi"])){
                $feilvdi=trim($data["feilvdi"]);
               
                $where.="and ht.mbfyl>=$feilvdi ";
            }
            if(trim($data["feilvgao"])){
                $feilvgao=trim($data["feilvgao"]);
               
                $where.="and ht.mbfyl<=$feilvgao ";
            }
            //经销商
            if(trim($data["jxs_name"])){
                $jxs_name=trim($data["jxs_name"]);
               
                $where.="and j.title='{$jxs_name}' ";
            }
            //合同编号
            if(trim($data["htbh"])){
                $htbh=trim($data["htbh"]);
               
                $where.="and ht.htbh='$htbh' ";
            }
            //合同名称
            if(trim($data["htmc"])){
                $htmc=trim($data["htmc"]);
               
                $where.="and ht.ht_mc='$htmc' ";
            }
            //合同有效期
            if(trim($data["start1"])){
                $start1=strtotime(trim($data["start1"]));
                $where.="and ht.start>=$start1 ";
            }
            if(trim($data["end1"])){
                $end1=strtotime(trim($data["end1"]));
                $where.="and ht.end<=$end1 ";
            }
            //授权
             if(trim($data["pp"])){
                $pp=trim($data["pp"]);
               
                $where.="and ht.sqppstr like '%{$pp}%' ";
            }
             if(trim($data["pl"])){
                $pl=trim($data["pl"]);
               
                $where.="and ht.sqplstr like '%{$pl}%' ";
            }
            if(trim($data["sqxt"])){
                $sqxt=trim($data["sqxt"]);
               
                $where.="and ht.sqxt='$sqxt' ";
            }
            //销售目标
            if(trim($data["tardi"])){
                $tardi=trim($data["tardi"]);
               
                $where.="and ht.htxsmb>=$tardi ";
            }
            if(trim($data["targao"])){
                $targao=trim($data["targao"]);
               
                $where.="and ht.htxsmb<=$targao ";
            }
            //状态
            if($data["st"])
                $where.="and ht.state={$data["st"]} ";
            if(trim($data["em_name"])){
                $em_name=trim($data["em_name"]);
               
                $where.="and e.em_name='$em_name' ";
            }
        }else{
            $data=["start"=>"","end"=>"","fenqu"=>"","sheng"=>"","shi"=>"","feilvdi"=>"","feilvgao"=>"","jxs_name"=>"","htbh"=>"","htmc"=>"","start1"=>"",
                    "end1"=>"","pp"=>"","pl"=>"","sqxt"=>"","tardi"=>"","targao"=>"","st"=>0,"em_name"=>""
            ];
        }

        $sum=Db::table("jxs_hetong")->alias("ht")
        ->join("ti_state st","ht.state=st.id")
        ->join("cg_jxs j","ht.jxs=j.id")
        ->join("employee e","ht.cuser=e.id")
        ->where($where)->count();
        $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;

        $apply=Db::table("jxs_hetong")->alias("ht")
        ->join("ti_state st","ht.state=st.id")
        ->join("cg_jxs j","ht.jxs=j.id")
        ->join("employee e","ht.cuser=e.id")
        ->where($where)
        ->order("ht.id desc")->limit($start,$list)
        ->field("ht.id,ht.htbh,ht.htmc_nf,j.title as jxs_name,st.title as zhuangtai,e.em_name,ht.ctime,ht.state as sid")
        ->select();
        for($i=0;$i<count($apply);$i++)
        {
            $apply[$i]["ctime"]=date("Y-m-d",$apply[$i]["ctime"]);
            $apply[$i]["myId"]=Db::table("cg_workflow")->where(["yw_id"=>$apply[$i]["id"],"ywlx"=>7])->value("id");
        }
        $this->assign("apply",$apply);
        $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);
        $this->assign("data",$data);

        return $this->fetch();
    }
        //经销商合同所有
    public function all($page=1,$list=10){
        $request = Request::instance();$data = $request->post();
        $state=Db::table("ti_state")->order("paixu")->select();

        $this->assign("state",$state);
        //$eid=Session::get("employee_id");
        $where="ht.is_deleted=0 ";
        if($data){
            //签署时间
            if(trim($data["start"])){
                $start=strtotime(trim($data["start"]));
                $where.="and ht.qstime>=$start ";
            }
            if(trim($data["end"])){
                $end=strtotime(trim($data["end"]));
                $where.="and ht.qstime<=$end ";
            }
            //地区
            if(trim($data["fenqu"])){
                $fenqu=trim($data["fenqu"]);
                $tmp=Db::table("cg_market_zoning")->where(["title"=>$fenqu])->field("id")->find();
                if($tmp)
                    $fenqu=$tmp["id"];
                else
                    $fenqu=-1;
                $where.="and j.zoning=$fenqu ";
            }
            if(trim($data["sheng"])){
                $sheng=trim($data["sheng"]);
                $tmp=Db::table("cg_market_provice")->where(["title"=>$sheng])->field("id")->find();
                if($tmp)
                    $sheng=$tmp["id"];
                else
                    $sheng=-1;
                $where.="and j.provice=$fenqu ";
            }
            if(trim($data["shi"])){
                $shi=trim($data["shi"]);
                $tmp=Db::table("cg_market_city")->where(["title"=>$shi])->field("id")->find();
                if($tmp)
                    $shi=$tmp["id"];
                else
                    $shi=-1;
                $where.="and j.city=$fenqu ";
            }
            //合同费用率
            if(trim($data["feilvdi"])){
                $feilvdi=trim($data["feilvdi"]);
               
                $where.="and ht.mbfyl>=$feilvdi ";
            }
            if(trim($data["feilvgao"])){
                $feilvgao=trim($data["feilvgao"]);
               
                $where.="and ht.mbfyl<=$feilvgao ";
            }
            //经销商
            if(trim($data["jxs_name"])){
                $jxs_name=trim($data["jxs_name"]);
               
                $where.="and j.title='{$jxs_name}' ";
            }
            //合同编号
            if(trim($data["htbh"])){
                $htbh=trim($data["htbh"]);
               
                $where.="and ht.htbh='$htbh' ";
            }
            //合同名称
            if(trim($data["htmc"])){
                $htmc=trim($data["htmc"]);
               
                $where.="and ht.ht_mc='$htmc' ";
            }
            //合同有效期
            if(trim($data["start1"])){
                $start1=strtotime(trim($data["start1"]));
                $where.="and ht.start>=$start1 ";
            }
            if(trim($data["end1"])){
                $end1=strtotime(trim($data["end1"]));
                $where.="and ht.end<=$end1 ";
            }
            //授权
             if(trim($data["pp"])){
                $pp=trim($data["pp"]);
               
                $where.="and ht.sqppstr like '%{$pp}%' ";
            }
             if(trim($data["pl"])){
                $pl=trim($data["pl"]);
               
                $where.="and ht.sqplstr like '%{$pl}%' ";
            }
            if(trim($data["sqxt"])){
                $sqxt=trim($data["sqxt"]);
               
                $where.="and ht.sqxt='$sqxt' ";
            }
            //销售目标
            if(trim($data["tardi"])){
                $tardi=trim($data["tardi"]);
               
                $where.="and ht.htxsmb>=$tardi ";
            }
            if(trim($data["targao"])){
                $targao=trim($data["targao"]);
               
                $where.="and ht.htxsmb<=$targao ";
            }
            //状态
            if($data["st"])
                $where.="and ht.state={$data["st"]} ";
            if(trim($data["em_name"])){
                $em_name=trim($data["em_name"]);
               
                $where.="and e.em_name='$em_name' ";
            }
        }else{
            $data=["start"=>"","end"=>"","fenqu"=>"","sheng"=>"","shi"=>"","feilvdi"=>"","feilvgao"=>"","jxs_name"=>"","htbh"=>"","htmc"=>"","start1"=>"",
                    "end1"=>"","pp"=>"","pl"=>"","sqxt"=>"","tardi"=>"","targao"=>"","st"=>0,"em_name"=>""
            ];
        }

        $sum=Db::table("jxs_hetong")->alias("ht")
        ->join("ti_state st","ht.state=st.id")
        ->join("cg_jxs j","ht.jxs=j.id")
        ->join("employee e","ht.cuser=e.id")
        ->where($where)->count();
        $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;

        $apply=Db::table("jxs_hetong")->alias("ht")
        ->join("ti_state st","ht.state=st.id")
        ->join("cg_jxs j","ht.jxs=j.id")
        ->join("employee e","ht.cuser=e.id")
        ->where($where)
        ->order("ht.id desc")->limit($start,$list)
        ->field("ht.id,ht.htbh,ht.htmc_nf,j.title as jxs_name,st.title as zhuangtai,e.em_name,ht.ctime,ht.state as sid")
        ->select();
        for($i=0;$i<count($apply);$i++)
        {
            $apply[$i]["ctime"]=date("Y-m-d",$apply[$i]["ctime"]);
            $apply[$i]["myId"]=Db::table("cg_workflow")->where(["yw_id"=>$apply[$i]["id"],"ywlx"=>7])->value("id");
        }
        $this->assign("apply",$apply);
        $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);
        $this->assign("data",$data);

        return $this->fetch();
    }
    //部门
    public function bumen($page=1,$list=10){
        $request = Request::instance();$data = $request->post();
        $state=Db::table("ti_state")->order("paixu")->select();

        $this->assign("state",$state);
        $eid=Session::get("employee_id");
        $user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->where("em.id=$eid and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id")
            ->find();
        $bumen=$user["de_name"];
        $where="ht.is_deleted=0 and de.index=1 and d.de_name='$bumen' ";
        if($data){
            //签署时间
            if(trim($data["start"])){
                $start=strtotime(trim($data["start"]));
                $where.="and ht.qstime>=$start ";
            }
            if(trim($data["end"])){
                $end=strtotime(trim($data["end"]));
                $where.="and ht.qstime<=$end ";
            }
            //地区
            if(trim($data["fenqu"])){
                $fenqu=trim($data["fenqu"]);
                $tmp=Db::table("cg_market_zoning")->where(["title"=>$fenqu])->field("id")->find();
                if($tmp)
                    $fenqu=$tmp["id"];
                else
                    $fenqu=-1;
                $where.="and j.zoning=$fenqu ";
            }
            if(trim($data["sheng"])){
                $sheng=trim($data["sheng"]);
                $tmp=Db::table("cg_market_provice")->where(["title"=>$sheng])->field("id")->find();
                if($tmp)
                    $sheng=$tmp["id"];
                else
                    $sheng=-1;
                $where.="and j.provice=$fenqu ";
            }
            if(trim($data["shi"])){
                $shi=trim($data["shi"]);
                $tmp=Db::table("cg_market_city")->where(["title"=>$shi])->field("id")->find();
                if($tmp)
                    $shi=$tmp["id"];
                else
                    $shi=-1;
                $where.="and j.city=$fenqu ";
            }
            //合同费用率
            if(trim($data["feilvdi"])){
                $feilvdi=trim($data["feilvdi"]);
               
                $where.="and ht.mbfyl>=$feilvdi ";
            }
            if(trim($data["feilvgao"])){
                $feilvgao=trim($data["feilvgao"]);
               
                $where.="and ht.mbfyl<=$feilvgao ";
            }
            //经销商
            if(trim($data["jxs_name"])){
                $jxs_name=trim($data["jxs_name"]);
               
                $where.="and j.title='{$jxs_name}' ";
            }
            //合同编号
            if(trim($data["htbh"])){
                $htbh=trim($data["htbh"]);
               
                $where.="and ht.htbh='$htbh' ";
            }
            //合同名称
            if(trim($data["htmc"])){
                $htmc=trim($data["htmc"]);
               
                $where.="and ht.ht_mc='$htmc' ";
            }
            //合同有效期
            if(trim($data["start1"])){
                $start1=strtotime(trim($data["start1"]));
                $where.="and ht.start>=$start1 ";
            }
            if(trim($data["end1"])){
                $end1=strtotime(trim($data["end1"]));
                $where.="and ht.end<=$end1 ";
            }
            //授权
             if(trim($data["pp"])){
                $pp=trim($data["pp"]);
               
                $where.="and ht.sqppstr like '%{$pp}%' ";
            }
             if(trim($data["pl"])){
                $pl=trim($data["pl"]);
               
                $where.="and ht.sqplstr like '%{$pl}%' ";
            }
            if(trim($data["sqxt"])){
                $sqxt=trim($data["sqxt"]);
               
                $where.="and ht.sqxt='$sqxt' ";
            }
            //销售目标
            if(trim($data["tardi"])){
                $tardi=trim($data["tardi"]);
               
                $where.="and ht.htxsmb>=$tardi ";
            }
            if(trim($data["targao"])){
                $targao=trim($data["targao"]);
               
                $where.="and ht.htxsmb<=$targao ";
            }
            //状态
            if($data["st"])
                $where.="and ht.state={$data["st"]} ";
            if(trim($data["em_name"])){
                $em_name=trim($data["em_name"]);
               
                $where.="and e.em_name='$em_name' ";
            }
        }else{
            $data=["start"=>"","end"=>"","fenqu"=>"","sheng"=>"","shi"=>"","feilvdi"=>"","feilvgao"=>"","jxs_name"=>"","htbh"=>"","htmc"=>"","start1"=>"",
                    "end1"=>"","pp"=>"","pl"=>"","sqxt"=>"","tardi"=>"","targao"=>"","st"=>0,"em_name"=>""
            ];
        }

        $sum=Db::table("jxs_hetong")->alias("ht")
        ->join("ti_state st","ht.state=st.id")
        ->join("cg_jxs j","ht.jxs=j.id")
        ->join("employee e","ht.cuser=e.id")
        ->join("department_employee de","de.employee_id=e.id")
        ->join("department d","de.department_id=d.id")
        ->where($where)->count();
        $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;

        $apply=Db::table("jxs_hetong")->alias("ht")
        ->join("ti_state st","ht.state=st.id")
        ->join("cg_jxs j","ht.jxs=j.id")
        ->join("employee e","ht.cuser=e.id")
        ->join("department_employee de","de.employee_id=e.id")
        ->join("department d","de.department_id=d.id")
        ->where($where)
        ->order("ht.id desc")->limit($start,$list)
        ->field("ht.id,ht.htbh,ht.htmc_nf,j.title as jxs_name,st.title as zhuangtai,e.em_name,ht.ctime,ht.state as sid")
        ->select();
        for($i=0;$i<count($apply);$i++)
        {
            $apply[$i]["ctime"]=date("Y-m-d",$apply[$i]["ctime"]);
            $apply[$i]["myId"]=Db::table("cg_workflow")->where(["yw_id"=>$apply[$i]["id"],"ywlx"=>7])->value("id");
        }
        $this->assign("apply",$apply);
        $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);
        $this->assign("data",$data);

        return $this->fetch();
    }
    
    //新增合同
    public function add($kid=null){
        //查询营业地址所有的省份
      
        
        $provices = db('cg_provice')->field('id,title')->select();
        $cities = db('cg_city')->field('id,title,provice as pid')->select();
        $counties = db('cg_county')->field('id,title,city as pid')->select();
        $this->assign([
            'provices'=>$provices,
            'cities' =>$cities,
            'counties' =>$counties,
        ]);
        if($kid){
            $apply=Db::table("jxs_hetong")->where(["id"=>$kid])->find();
            $apply["start"]=date("Y-m-d",$apply["start"]);
            $apply["end"]=date("Y-m-d",$apply["end"]);
            $apply["qstime"]=date("Y-m-d",$apply["qstime"]);
            $this->assign("apply",$apply);
            $jxs=Db::table("cg_jxs")->where("id={$apply["jxs"]}")->find();
        $jxs['cooptime'] = $this->DiffDate(date('Y-m-d',$jxs['cooptime']),date('Y-m-d'));
        $jxs['qudao']=Db::table("cg_channel_types1")->where("id={$jxs["channeltype"]}")->value("title");
        
        $this->assign("jxs",$jxs);
                 //查询合同提交人信息
            $eid=$apply["cuser"];

            $user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->where("em.id=$eid and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id")
            ->find();
            $today=date("Y-m-d",$apply["ctime"]);
            if($apply["fujian"])
                $fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
            else
                $fujian=[];
            //明细处理
            $mx=Db::table("jxs_hetong_fenjie")->where(["hid"=>$kid])->find();
            $lans=json_decode($mx["prolist"],true);
            $this->assign("lans",$lans);
            $xh=count($lans);
            $this->assign("xh",$xh);
            $mx["kaohe2"]=json_decode($mx["kaohe2"],true);
            $sale_target=json_decode($mx["sale_target"],true);
            $yusuan_target=json_decode($mx["yusuan_target"],true);
            $kaohe2str=implode(',',$mx["kaohe2"]);
            $kaohe2=Db::table("cg_cainian")->alias("c")
            ->join("cg_kaoheqi1 k1","k1.cid=c.id")
            ->join("cg_kaoheqi2 k2","k2.pid=k1.id")
            ->where("k2.id in ($kaohe2str)")
            ->field("c.title as cainian,c.id as cid,k2.title as yue,k2.id as k2id")
            ->select();
            //if()
            $this->assign("kaohe2",$kaohe2);
            $this->assign("sale_target",$sale_target);
            $this->assign("yusuan_target",$yusuan_target);
        }else{
               //查询合同提交人信息
            $eid=Session::get("employee_id");

            $user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->where("em.id=$eid and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id")
            ->find();
            $today=date("Y-m-d");

            $fujian=[];
        }
        $this->assign("kid",$kid);
        $this->assign("user",$user);
        $this->assign("fujian",$fujian);
        $this->assign("today",$today);
        return $this->fetch();
    }
    //新增合同处理
    public function addcaozuo(){
        $request = Request::instance();$data = $request->post();
       // print_r($data);exit;
        $adddata["state"]=$data["state"];
        //经销商
        if($data["jxs"])
            $adddata["jxs"]=$data["jxs"];
        else
             return json_encode(["msg"=>"经销商必须选择","state"=>2]);
        //营业地址类型
        $adddata["yydzlx"]=$data["yydzlx"];
        //营业地址
        if($data["yydz_provice"])
            $adddata["yydz_provice"]=$data["yydz_provice"];
        else
            return json_encode(["msg"=>"经销商营业地址必须填写完整","state"=>2]);
        if($data["yydz_city"])
            $adddata["yydz_city"]=$data["yydz_city"];
        else
            return json_encode(["msg"=>"经销商营业地址必须填写完整","state"=>2]);
        if($data["yydz_county"])
            $adddata["yydz_county"]=$data["yydz_county"];
        else
            return json_encode(["msg"=>"经销商营业地址必须填写完整","state"=>2]);
        if(trim($data["yddz_xxdz"]))
            $adddata["yddz_xxdz"]=trim($data["yddz_xxdz"]);
        else
            return json_encode(["msg"=>"经销商营业地址必须填写完整","state"=>2]);
        //合同年份
        if(trim($data["htmc_nf"]))
            $adddata["htmc_nf"]=trim($data["htmc_nf"]);
        else
            return json_encode(["msg"=>"合同年份必须填写完整","state"=>2]);
        //合同编号
        $adddata["htbh"]=$data["htbh"];
        $jxstitle=Db::table("cg_jxs")->where(["id"=>$data["jxs"]])->value("title");
        $adddata["ht_mc"]=$jxstitle."-".$adddata["htmc_nf"]."年合同";
        $adddata["title"]=$jxstitle."-".$adddata["htmc_nf"]."年合同";
        //合同有效期
        if($data["htyxq_start"])
            $adddata["start"]=strtotime($data["htyxq_start"]);
        else
            return json_encode(["msg"=>"合同有效期必须填写完整","state"=>2]);
        if($data["htyxq_end"])
            $adddata["end"]=strtotime($data["htyxq_end"]);
        else
            return json_encode(["msg"=>"合同有效期必须填写完整","state"=>2]);
        //合同销售目标
        if($data["htxsmb"])
            $adddata["htxsmb"]=$data["htxsmb"];
        else
            return json_encode(["msg"=>"合同销售目标必须填写完整","state"=>2]);
        if($data["ysfymb"])
            $adddata["ysfymb"]=$data["ysfymb"];
        else
            return json_encode(["msg"=>"预算费用目标必须填写完整","state"=>2]);
        //目标费用率
        if($data["mbfyl"])
            $adddata["mbfyl"]=$data["mbfyl"];
        else
            return json_encode(["msg"=>"目标费用率必须填写完整","state"=>2]);
        //授权品牌
        if($data["sqpp"]){
            $adddata["sqpp"]=$data["sqpp"];
            $adddata["sqppstr"]=$data["sqppstr"];
        }else
            return json_encode(["msg"=>"授权品牌必须选择","state"=>2]);
        //授权品类
        if($data["sqpl"]){
            $adddata["sqpl"]=$data["sqpl"];
            $adddata["sqplstr"]=$data["sqplstr"];
        }else
            return json_encode(["msg"=>"授权品类必须选择","state"=>2]);
        //经销类型
        $adddata["jxlx"]=$data["jxlx"];
        if($data["jxlx"]==1){
            //区域经销
            if($data["sqqy"]){
                $adddata["sqqy"]=$data["sqqy"];
                $adddata["sqqystr"]=$data["sqqystr"];

            }else{
                return json_encode(["msg"=>"授权区域必须选择","state"=>2]);
            }
        }else{
            //系统经销
            if(trim($data["sqxt"]))
                $adddata["sqxt"]=$data["sqxt"];
            else
                return json_encode(["msg"=>"授权系统必须填写","state"=>2]);
        }
        //法人
        if(trim($data["cw_legalrepre"]))
            $adddata["cw_legalrepre"]=trim($data["cw_legalrepre"]);
        else
            return json_encode(["msg"=>"法定代表人必须填写","state"=>2]);
        $adddata["cw_lrphone"]=$data["cw_lrphone"];
        $adddata["cw_lrmobile"]=$data["cw_lrmobile"];
        $adddata["cw_lremail"]=$data["cw_lremail"];
        $adddata["cw_qualification"]=$data["cw_qualification"];
        if(trim($data["cw_taxsn"]))
            $adddata["cw_taxsn"]=trim($data["cw_taxsn"]);
        else
            return json_encode(["msg"=>"税号必须填写","state"=>2]);
        if(trim($data["cw_bank"]))
            $adddata["cw_bank"]=trim($data["cw_bank"]);
        else
            return json_encode(["msg"=>"开户行必须填写","state"=>2]);
        if(trim($data["cw_banksn"]))
            $adddata["cw_banksn"]=trim($data["cw_banksn"]);
        else
            return json_encode(["msg"=>"开户行帐号必须填写","state"=>2]);
        if(trim($data["cw_mailaddr"]))
            $adddata["cw_mailaddr"]=trim($data["cw_mailaddr"]);
        else
            return json_encode(["msg"=>"邮寄地址必须填写","state"=>2]);
        if(trim($data["cw_zipcode"]))
            $adddata["cw_zipcode"]=trim($data["cw_zipcode"]);
        else
            return json_encode(["msg"=>"邮寄地址邮编必须填写","state"=>2]);
        $adddata["cw_contact"]=$data["cw_contact"];
        $adddata["cw_phone"]=$data["cw_phone"];
        $adddata["cw_email"]=$data["cw_email"];
        //业务联系人
        if(trim($data["bs_contact"]))
            $adddata["bs_contact"]=trim($data["bs_contact"]);
        else
            return json_encode(["msg"=>"业务联系人必须填写","state"=>2]);
        if(trim($data["bs_phone"]))
            $adddata["bs_phone"]=trim($data["bs_phone"]);
        else
            return json_encode(["msg"=>"业务联系人电话必须填写","state"=>2]);
        if(trim($data["bs_mobile"]))
            $adddata["bs_mobile"]=trim($data["bs_mobile"]);
        else
            return json_encode(["msg"=>"业务联系人手机必须填写","state"=>2]);
        if(trim($data["bs_fax"]))
            $adddata["bs_fax"]=trim($data["bs_fax"]);
        else
            return json_encode(["msg"=>"业务联系人传真必须填写","state"=>2]);
        if(trim($data["bs_rcv_unit"]))
            $adddata["bs_rcv_unit"]=trim($data["bs_rcv_unit"]);
        else
            return json_encode(["msg"=>"收货单位必须填写","state"=>2]);
        if(trim($data["bs_rcv_addr"]))
            $adddata["bs_rcv_addr"]=trim($data["bs_rcv_addr"]);
        else
            return json_encode(["msg"=>"业务收货地址必须填写","state"=>2]);
        if(trim($data["bs_rcv_one"]))
            $adddata["bs_rcv_one"]=trim($data["bs_rcv_one"]);
        else
            return json_encode(["msg"=>"业务收货人必须填写","state"=>2]);
        if(trim($data["bs_rcv_phone"]))
            $adddata["bs_rcv_phone"]=trim($data["bs_rcv_phone"]);
        else
            return json_encode(["msg"=>"业务收货人电话必须填写","state"=>2]);
        //合同签署情况
        if($data["qstime"])
            $adddata["qstime"]=strtotime($data["qstime"]);
        else
            return json_encode(["msg"=>"合同签署日期必须填写","state"=>2]);
        if($data["wofanguser"])
            $adddata["wofanguser"]=$data["wofanguser"];
        else
            return json_encode(["msg"=>"我方签署人必须填写","state"=>2]);
        if(trim($data["df_ren"]))
            $adddata["df_ren"]=trim($data["df_ren"]);
        else
            return json_encode(["msg"=>"对方签署人必须填写","state"=>2]);
        if(trim($data["df_job"]))
            $adddata["df_job"]=trim($data["df_job"]);
        else
            return json_encode(["msg"=>"对方签署人职位必须填写","state"=>2]);
        if(trim($data["df_phone"]))
            $adddata["df_phone"]=trim($data["df_phone"]);
        else
            return json_encode(["msg"=>"对方签署人电话必须填写","state"=>2]);
        if(trim($data["df_email"]))
            $adddata["df_email"]=trim($data["df_email"]);
        else
            return json_encode(["msg"=>"对方签署人邮箱必须填写","state"=>2]);
        if(trim($data["df_addr"]))
            $adddata["df_addr"]=trim($data["df_addr"]);
        else
            return json_encode(["msg"=>"对方签署人地址必须填写","state"=>2]);
        //特殊合同
        $adddata["ts"]=$data["ts"];
        //特殊说明
        if($data["ts"]){
            if(trim($data["tsmiaoshu"]))
                $adddata["tsmiaoshu"]=trim($data["tsmiaoshu"]);
            else
                return json_encode(["msg"=>"特殊条款备注必须填写","state"=>2]);
        }
        if(trim($data["miaoshu"]))
            $adddata["miaoshu"]=trim($data["miaoshu"]);
        else
            return json_encode(["msg"=>"合同描述必须填写","state"=>2]);
        //附件
        $adddata["fujian"]=$data["attach"];
        //明细类型
        $adddata["detail_type"]=$data["mxtype"];
        //分解类型
        $typename="默认";
        switch ($adddata["detail_type"]) {
            case 2:
                # code...
                $typename="品牌";
                break;
            case 3:
                # code...
                $typename="品类";
                break;
            case 4:
                # code...
                $typename="系列";
                break;
        }
        //return json_encode(["msg"=>"完成","state"=>2]);
        //明细分解
        $mxdata["detail_type"]=$data["mxtype"];
        if($data["mxtype"]==1){
            $mxdata["prolist"]=[];
        }else{
            if(isset($data["prolist"])){
                for($i=0;$i<count($data["prolist"]);$i++){
                    if(trim($data["prolist"][$i]))
                        $data["prolist"][$i]=trim($data["prolist"][$i]);
                    else
                        return json_encode(["msg"=>"存在未填写名称的{$typename}","state"=>2]);
                }
                $mxdata["prolist"]=json_encode($data["prolist"]);
            }else{
                
                return json_encode(["msg"=>"目标分解中至少添加一个{$typename}","state"=>2]);
            }
        }
        //分解金额
        //print_r($data["sale_target"]);exit;
        if(isset($data["sale_target"])){
            $mxdata["sale_target"]=json_encode($data["sale_target"]);
        }else{
            return json_encode(["msg"=>"目标分解中至少存在一条明细","state"=>2]);
        }
        if(isset($data["yusuan_target"])){
            $mxdata["yusuan_target"]=json_encode($data["yusuan_target"]);
        }else{
            return json_encode(["msg"=>"目标分解中至少存在一条明细","state"=>2]);
        }

        if(isset($data["kaohe2"])){
            $mxdata["kaohe2"]=json_encode($data["kaohe2"]);
        }else{
            return json_encode(["msg"=>"目标分解中至少存在一条明细","state"=>2]);
        }
        //echo $mxdata["yusuan_target"];exit;
        if($data["kid"]){
            //修改
            $adddata["puser"]=Session::get("employee_id");
            $adddata["ptime"]=time();
            $adddata["id"]=$data["kid"];
            Db::startTrans();
            try{
                $res1=Db::table("jxs_hetong")->update($adddata);
                
                $res2=Db::table("jxs_hetong_fenjie")->where(["hid"=>$data["kid"]])->update($mxdata);
            }catch (\Exception $e) {
                Db::rollBack();
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            if ($res1) {
                if($data["state"]==3){
                        $back=$this->work(7,$data["kid"]);
                        $backarr=json_decode($back,true);
                        if($backarr["state"]!=1){
                            Db::rollBack();
                            return $back;
                        }
                }
                Db::commit();
                return json_encode(["msg"=>"","state"=>1]);
            } else{
                 Db::rollBack();
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
        }else{
            //生成单号
            $timenow=date("Ymd");
            $num=Db::table("jxs_hetong")->where("no like '$timenow%'")->count();
            $num++;
            $strnum=$timenow.sprintf("%05d", $num);
            $adddata["no"]=$strnum;
            $adddata["cuser"]=Session::get("employee_id");
            $adddata["puser"]=Session::get("employee_id");
            $adddata["ctime"]=time();
            $adddata["ptime"]=time();
            //新增
            Db::startTrans();
            try{
                $res1=Db::table("jxs_hetong")->insertGetId($adddata);
                $mxdata["hid"]=$res1;
                $res2=Db::table("jxs_hetong_fenjie")->insert($mxdata);
            }catch (\Exception $e) {
                Db::rollBack();
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            if ($res1&&$res2) {
                if($data["state"]==3){
                        $back=$this->work(7,$res1);
                        $backarr=json_decode($back,true);
                        if($backarr["state"]!=1){
                            Db::rollBack();
                            return $back;
                        }
                }
                Db::commit();
                return json_encode(["msg"=>"","state"=>1]);
            } else{
                 Db::rollBack();
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
        }
    }
    public function xiugaihetonghao($year,$jid){
        $jxs = db('cg_jxs')->where('id',$jid)
        ->field('sn,cooptime,channeltype,addr,cw_legalrepre,cw_lrphone,cw_lrmobile,cw_lremail,cw_qualification,cw_taxsn,cw_bank,cw_banksn,cw_mailaddr,cw_zipcode,cw_contact,cw_phone,cw_email,bs_contact,bs_phone,bs_mobile,bs_fax,bs_rcv_unit,bs_rcv_addr,bs_rcv_one,title')
        ->find();
        $jxs['htbh'] = $year.'-'.$jxs['sn'];
        $bhc=Db::table("jxs_hetong")->where("htbh like '{$jxs["htbh"]}%'")->count();
        if($bhc)
            $jxs['htbh']=$jxs['htbh']."-".$bhc;
        return $jxs['htbh'];
    }
    //查询经销商并生成合同编号
    public function jxs(){
        $id = $this->request->param('id');
        $jxs = db('cg_jxs')->where('id',$id)
        ->field('sn,cooptime,channeltype,addr,cw_legalrepre,cw_lrphone,cw_lrmobile,cw_lremail,cw_qualification,cw_taxsn,cw_bank,cw_banksn,cw_mailaddr,cw_zipcode,cw_contact,cw_phone,cw_email,bs_contact,bs_phone,bs_mobile,bs_fax,bs_rcv_unit,bs_rcv_addr,bs_rcv_one,title')
        ->find();
        $jxs['cooptime'] = $this->DiffDate(date('Y-m-d',$jxs['cooptime']),date('Y-m-d'));

        //生成合同编号
        $jxs['htbh'] = date('Y').'-'.$jxs['sn'];
        $bhc=Db::table("jxs_hetong")->where("htbh like '{$jxs["htbh"]}%'")->count();
        if($bhc)
            $jxs['htbh']=$jxs['htbh']."-".$bhc;
        $tmp=Db::table("cg_channel_types1")->where(["id"=>$jxs["channeltype"]])->find();
        $jxs["channeltype"]=$tmp["title"];
        echo json_encode($jxs);
    }
    /**
    +----------------------------------------------------------
     * 功能：计算两个日期相差 年 月 日
    +----------------------------------------------------------
     * @param date   $date1 起始日期
     * @param date   $date2 截止日期日期
    +----------------------------------------------------------
     * @return array
    +----------------------------------------------------------
     */
    function DiffDate($date1, $date2) {
        if (strtotime($date1) > strtotime($date2)) {
            $ymd = $date2;
            $date2 = $date1;
            $date1 = $ymd;
        }
        list($y1, $m1, $d1) = explode('-', $date1);
        list($y2, $m2, $d2) = explode('-', $date2);
        $y = $m = $d = $_m = 0;
        $math = ($y2 - $y1) * 12 + $m2 - $m1;
        $y = round($math / 12);
        $m = intval($math % 12);
        $d = (mktime(0, 0, 0, $m2, $d2, $y2) - mktime(0, 0, 0, $m2, $d1, $y2)) / 86400;
        if ($d < 0) {
            $m -= 1;
            $d += date('j', mktime(0, 0, 0, $m2, 0, $y2));
        }
        $m < 0 && $y -= 1;
        return $y.'年'.$m.'个月'.$d.'天';
    }
    //选择系列弹框
    public function selectseries(){
        return $this->fetch();
    }
     //选择系列弹框
    public function selectproduct(){
        return $this->fetch();
    }
     //产品树
    public function protree(){
        $data = Db::table('pro_products')
            ->where("is_actived=1 and is_deleted=0")
            ->field('id,pro_name as title')
            ->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            $temp['id'] = $v['id'];
//            $temp["chkDisabled"]=true;
//            $temp["nocheck"]=true;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }
    //系列树
    public function seriestree(){
        $data = Db::table('pro_series')
            ->where("is_actived=1 and is_deleted=0")
            ->field('id,series_name as title')
            ->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            $temp['id'] = $v['id'];
//            $temp["chkDisabled"]=true;
//            $temp["nocheck"]=true;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }
    public function getp($zid){
        $provices=Db::table("cg_market_provice")->where("zoning=$zid")->field("id,title,zoning as pid")->select();
        return json_encode($provices);
    }
     public function getc($pid){
        $provices=Db::table("cg_market_city")->where("provice=$pid")->field("id,title")->select();
        return json_encode($provices);
    }
    //开户申请
    public function kaihu($kid=null){
        $this->assign("kid",$kid);
        if($kid){

          
        }else{
            //查询合同提交人信息
            $eid=Session::get("employee_id");

            $user=Db::table("employee")->alias("em")
            ->join("department_employee de","de.employee_id=em.id")
            ->join("department d","de.department_id=d.id")
            ->where("em.id=$eid and de.index=1")
            ->field("em.em_name,d.de_name,em.mobile,em.id")
            ->find();
            $cday=date("Y-m-d");
            $no="";
            $year=intval(date("Y"))-1;
            $fujian=[];
        }
        //省市区
        $zon=Db::table("cg_market_zoning")->field("id,title")->select();
        $provices=Db::table("cg_market_provice")->field("id,title,zoning as pid")->select();
        $citys=Db::table("cg_market_city")->field("id,title,provice as pid")->select();
        $ct=Db::table("cg_channel_types1")->select();
        $this->assign("ct",$ct);
        $this->assign("citys",$citys);
        $this->assign("provices",$provices);
        $this->assign("zon",$zon);
        $this->assign("user",$user);//申请人信息
        $this->assign("no",$no);//申请单编号
        $this->assign("cday",$cday);//申请日期
        $this->assign("year",$year);//表单申请的上一年
        $this->assign("fujian",$fujian);
        return $this->fetch();
    }
    //开户申请操作
    public function kaihucaozuo(){
        $request = Request::instance();$data = $request->post();
        //echo $data["miaoshu"];exit;
        $preg_mobile="/^1[34578]\d{9}$/"; 
        $preg_code="/^\d{6}$/";
        $preg_phone_qu="/^0\d{2,3}$/";
        $preg_phone="/^\d{8}$/";
        $preg_idcard1="/^\d{15}$/";
        $preg_idcard2="/^\d{17}[0-9Xx]$/";
        $preg_email="/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/";
         //验证联系人电话
            if(preg_match($preg_mobile, $data["lianxiphone"])){
                $adddata["lianxiphone"]= $data["lianxiphone"];
            }else{
                return json_encode(["msg"=>"联系人电话请正确填写11位手机号","state"=>2]);
            }
            //验证区域
            if($data["fenqu"]){
                $adddata["fenqu"]=$data["fenqu"];
            }else{
                return json_encode(["msg"=>"计划经营分区必须选择","state"=>2]);
            }
            if($data["sheng"]){
                $adddata["sheng"]=$data["sheng"];
            }else{
                return json_encode(["msg"=>"计划经营省份必须选择","state"=>2]);
            }
            if($data["shi"]){
                $adddata["shi"]=$data["shi"];
            }else{
                return json_encode(["msg"=>"计划经营城市必须选择","state"=>2]);
            }
            if(trim($data["qu"]))
                $adddata["qu"]=trim($data["qu"]);
            //验证计划时间
            if(trim($data["start"]))
                $adddata["start"]=strtotime($data["start"]);
            else
                return json_encode(["msg"=>"计划签约开始时间必须选择","state"=>2]);
            if(trim($data["end"]))
                $adddata["end"]=strtotime($data["end"]);
            else
                return json_encode(["msg"=>"计划签约结束时间必须选择","state"=>2]);
            //验证计划销售目标
            if($data["target_sale"]){
                if($data["target_sale"]>0)
                    $adddata["target_sale"]=$data["target_sale"];
                else
                    return json_encode(["msg"=>"计划月均销售目标必须是正数","state"=>2]);
            }
            else
                return json_encode(["msg"=>"计划月均销售目标不能为空","state"=>2]);
            //计划经营产品系列
            if($data["pros"])
                $adddata["pros"]=$data["pros"];
            else
                return json_encode(["msg"=>"请至少选择一款计划经营系列","state"=>2]);
            //验证经销商编号和名称
            if(trim($data["jxs_no"])){
                $adddata["jxs_no"]=trim($data["jxs_no"]);
                $has=Db::table("cg_jxs")->where(["sn"=>$adddata["jxs_no"]])->count();
                if($has)
                    return json_encode(["msg"=>"经销商编号已存在","state"=>2]);
            }
            else
                return json_encode(["msg"=>"经销商编号不能为空","state"=>2]);
            if(trim($data["jxs_name"])){
                $adddata["jxs_name"]=trim($data["jxs_name"]);
                $has=Db::table("cg_jxs")->where(["title"=>$adddata["jxs_name"]])->count();
                if($has)
                    return json_encode(["msg"=>"经销商名称已存在","state"=>2]);
            }
            else
                return json_encode(["msg"=>"经销商名称不能为空","state"=>2]);
            //经销商类型
            $adddata["jxs_type"]=$data["jxs_type"];
            //验证渠道占比
            if(trim($data["qudao1"]))
                $adddata["qudao1"]=trim($data["qudao1"]);
            else
                $adddata["qudao1"]=0;
            if(trim($data["qudao2"]))
                $adddata["qudao2"]=trim($data["qudao2"]);
            else
                $adddata["qudao2"]=0;
            if(trim($data["qudao3"]))
                $adddata["qudao3"]=trim($data["qudao3"]);
            else
                $adddata["qudao3"]=0;
            if(trim($data["qudao4"]))
                $adddata["qudao4"]=trim($data["qudao4"]);
            else
                $adddata["qudao4"]=0;
            $qudaozong=$adddata["qudao1"]+$adddata["qudao2"]+$adddata["qudao3"]+$adddata["qudao4"];
            if($qudaozong!=100)
                return json_encode(["msg"=>"四项销售渠道占比总和必须是100%","state"=>2]);
            //渠道类别
            if($data["channeltype"])
                $adddata["channeltype"]=$data["channeltype"];
            else
                return json_encode(["msg"=>"渠道类别必须选择","state"=>2]);
            //经营邮寄地址
            if(trim($data["dizhi"]))
                $adddata["dizhi"]=trim($data["dizhi"]);
            else
                return json_encode(["msg"=>"经营(邮寄)地址不能为空","state"=>2]);
            //邮编
            if(preg_match($preg_code, $data["code"])){
                $adddata["code"]= $data["code"];
            }else{
                return json_encode(["msg"=>"请正确填写经销商邮编","state"=>2]);
            }
            //纳税人资格
            $adddata["nashui"]=$data["nashui"];
            //纳税人登记号
            if(trim($data["nashui_no"]))
                $adddata["nashui_no"]=trim($data["nashui_no"]);
            else
                return json_encode(["msg"=>"纳税人登记号不能为空","state"=>2]);
            //法人
            if(trim($data["faren"]))
                $adddata["faren"]=trim($data["faren"]);
            else
                return json_encode(["msg"=>"法人不能为空","state"=>2]);
            //法人电话
            if(preg_match($preg_phone_qu, $data["faren_phone_qu"])){
                $adddata["faren_phone_qu"]= $data["faren_phone_qu"];
            }else{
                return json_encode(["msg"=>"请正确填写法人固话区号","state"=>2]);
            }
            if(preg_match($preg_phone, $data["faren_phone"])){
                $adddata["faren_phone"]= $data["faren_phone"];
            }else{
                return json_encode(["msg"=>"请正确填写法人固话","state"=>2]);
            }
            //传真
            if(preg_match($preg_phone_qu, $data["fax_qu"])){
                $adddata["fax_qu"]= $data["fax_qu"];
            }else{
                return json_encode(["msg"=>"请正确填写传真区号","state"=>2]);
            }
            if(preg_match($preg_phone, $data["fax"])){
                $adddata["fax"]= $data["fax"];
            }else{
                return json_encode(["msg"=>"请正确填写传真号","state"=>2]);
            }
            //法人手机
             if(preg_match($preg_mobile, $data["faren_mobile"])){
                $adddata["faren_mobile"]= $data["faren_mobile"];
            }else{
                return json_encode(["msg"=>"法人手机请正确填写11位手机号","state"=>2]);
            }
            //法人身份证
            if(preg_match($preg_idcard1, $data["faren_idcard"])||preg_match($preg_idcard2, $data["faren_idcard"])){
                $adddata["faren_idcard"]= $data["faren_idcard"];
            }else{
                return json_encode(["msg"=>"请正确输入15位或18位的法人身份证号","state"=>2]);
            }
            //法人类型
            $adddata["faren_type"]=$data["faren_type"];
            //总经理姓名
            if(trim($data["manager_name"]))
                $adddata["manager_name"]=trim($data["manager_name"]);
            else
                return json_encode(["msg"=>"总经理姓名不能为空","state"=>2]);
            //总经理手机
            if(preg_match($preg_mobile, $data["manager_mobile"])){
                $adddata["manager_mobile"]= $data["manager_mobile"];
            }else{
                return json_encode(["msg"=>"总经理手机请正确填写11位手机号","state"=>2]);
            }
            //总经理电子邮箱
            if(preg_match($preg_email, $data["manager_email"])){
                $adddata["manager_email"]= $data["manager_email"];
            }else{
                return json_encode(["msg"=>"请输入正确的总经理邮箱","state"=>2]);
            }
            //总经理身份证
            if(preg_match($preg_idcard1, $data["manager_idcard"])||preg_match($preg_idcard2, $data["manager_idcard"])){
                $adddata["manager_idcard"]= $data["manager_idcard"];
            }else{
                return json_encode(["msg"=>"请正确输入15位或18位的总经理身份证号","state"=>2]);
            }
            //总经理身份
            $adddata["manager_type"]=$data["manager_type"];
            //主要业务人员
            if(trim($data["main_sales"]))
                $adddata["main_sales"]=trim($data["manager_name"]);
            else
                return json_encode(["msg"=>"主要业务人员姓名不能为空","state"=>2]);
            //主要业务人员固定电话
            if(preg_match($preg_phone_qu, $data["main_sales_phone_qu"])){
                $adddata["main_sales_phone_qu"]= $data["main_sales_phone_qu"];
            }else{
                return json_encode(["msg"=>"请正确填写主要业务人员固话区号","state"=>2]);
            }
            if(preg_match($preg_phone, $data["main_sales_phone"])){
                $adddata["main_sales_phone"]= $data["main_sales_phone"];
            }else{
                return json_encode(["msg"=>"请正确填写主要业务人员固话","state"=>2]);
            }
            //主要业务人员传真
            if(preg_match($preg_phone_qu, $data["main_sales_fax_qu"])){
                $adddata["main_sales_fax_qu"]= $data["main_sales_fax_qu"];
            }else{
                return json_encode(["msg"=>"请正确填写主要业务人员传真区号","state"=>2]);
            }
            if(preg_match($preg_phone, $data["main_sales_fax"])){
                $adddata["main_sales_fax"]= $data["main_sales_fax"];
            }else{
                return json_encode(["msg"=>"请正确填写主要业务人员传真","state"=>2]);
            }
            //主要业务人员手机
            if(trim($data["main_sales_mobile"])){
                if(preg_match($preg_mobile, $data["main_sales_mobile"])){
                    $adddata["main_sales_mobile"]= $data["main_sales_mobile"];
                }else{
                    return json_encode(["msg"=>"主要业务人员手机请正确填写11位手机号","state"=>2]);
                }
            }
            //财务人员姓名
            if(trim($data["caiwu"]))
                $adddata["caiwu"]=trim($data["caiwu"]);
            else
                return json_encode(["msg"=>"财务负责人姓名不能为空","state"=>2]); 
            //财务人员固定电话
            if(preg_match($preg_phone_qu, $data["caiwu_phone_qu"])){
                $adddata["caiwu_phone_qu"]= $data["caiwu_phone_qu"];
            }else{
                return json_encode(["msg"=>"请正确填写财务负责人固话区号","state"=>2]);
            }
            if(preg_match($preg_phone, $data["caiwu_phone"])){
                $adddata["caiwu_phone"]= $data["caiwu_phone"];
            }else{
                return json_encode(["msg"=>"请正确填写财务负责人固话","state"=>2]);
            }
            //财务人员传真
            if(preg_match($preg_phone_qu, $data["caiwu_fax_qu"])){
                $adddata["caiwu_fax_qu"]= $data["caiwu_fax_qu"];
            }else{
                return json_encode(["msg"=>"请正确填写财务负责人传真区号","state"=>2]);
            }
            if(preg_match($preg_phone, $data["caiwu_fax"])){
                $adddata["caiwu_fax"]= $data["caiwu_fax"];
            }else{
                return json_encode(["msg"=>"请正确填写财务负责人传真","state"=>2]);
            }
             //财务手机
            if(trim($data["caiwu_mobile"])){
                if(preg_match($preg_mobile, $data["caiwu_mobile"])){
                    $adddata["caiwu_mobile"]= $data["caiwu_mobile"];
                }else{
                    return json_encode(["msg"=>"财务负责人手机请正确填写11位手机号","state"=>2]);
                }
            }
            //经销商位置
            $adddata["jxs_location"]=$data["jxs_location"];
            //是否在批发市场
            $adddata["is_pifa"]=$data["is_pifa"];
            //经销商人员数量
            if($data["jxs_manager_num"]){
                $adddata["jxs_manager_num"]=$data["jxs_manager_num"];
            }else{
                    return json_encode(["msg"=>"请填写经销商业务经理人数","state"=>2]);
            }
            if($data["jxs_sales_num"]){
                $adddata["jxs_sales_num"]=$data["jxs_sales_num"];
            }else{
                    return json_encode(["msg"=>"请填写经销商业务代表人数","state"=>2]);
            }
            if($data["jxs_caiwu_num"]!==""){
                $adddata["jxs_caiwu_num"]=$data["jxs_caiwu_num"];
            }else{
                    return json_encode(["msg"=>"请填写经销商会记人数","state"=>2]);
            }
            //业务负责人类型
            $adddata["fuzeren_type"]=$data["fuzeren_type"];
            //经销商车辆情况
            if($data["car_num"]!==""){
                $adddata["car_num"]=$data["car_num"];
            }else{
                    return json_encode(["msg"=>"请填写经销商货车数","state"=>2]);
            }
            if($data["zhen_car_num"]!==""){
                $adddata["zhen_car_num"]=$data["zhen_car_num"];
            }else{
                    return json_encode(["msg"=>"请填写经销商乡镇覆盖货车数","state"=>2]);
            }
            //注册资金
            if($data["zhucezijin"]){
                $adddata["zhucezijin"]=$data["zhucezijin"];
            }else{
                    return json_encode(["msg"=>"请填写经销商注册资金","state"=>2]);
            }
            //主要渠道
            if($data["main_channels"]){
                $adddata["main_channels"]=implode(',',$data["main_channels"]);
            }
            //经营网点大概
            if($data["tongnet"]!==""){
                $adddata["tongnet"]=$data["tongnet"];
            }else{
                    return json_encode(["msg"=>"请填写同品类网点数","state"=>2]);
            }
            if($data["butongnet"]!==""){
                $adddata["butongnet"]=$data["butongnet"];
            }else{
                    return json_encode(["msg"=>"请填写不同品类网点数","state"=>2]);
            }
            //辖区内全部网点//预计销售销路通产品的网点
            $sumall=0;$yujiall=0;$biliall=0;
            try{
                for($i=0;$i<count($data["alln"]);$i++){
                    if(!$data["alln"][$i])
                        $data["alln"][$i]=0;
                    $sumall+=$data["alln"][$i];
                    if(!$data["yujin"][$i])
                        $data["yujin"][$i]=0;
                    if($data["yujin"][$i]>$data["alln"][$i])
                        return json_encode(["msg"=>"预计销售销路通产品的网点不得超出辖区内的全部网点的数量","state"=>2]);

                    $yujiall+=$data["yujin"][$i];
                    if(!$data["weilain"][$i])
                        $data["weilain"][$i]=0;
                    if(!$data["bilin"][$i])
                        $data["bilin"][$i]=0;
                    $biliall+=$data["bilin"][$i];
                    if(!$data["yujijin"][$i])
                        $data["yujijin"][$i]=0;

                }
            }catch(\Exception $e){
               echo $e->getMessage();exit;
           
            }
            //echo 1;exit;
            if($sumall<=0)
                return json_encode(["msg"=>"辖区内的全部网点总数至少1家","state"=>2]);
            else
                $adddata["alln"]=implode(',',$data["alln"]);
            if($yujiall<=0)
                return json_encode(["msg"=>"预计销售销路通产品的网点总数至少1家","state"=>2]);
            else
                $adddata["yujin"]=implode(',',$data["yujin"]);
            $adddata["weilain"]=implode(',',$data["weilain"]);
            if($biliall!=100)
                return json_encode(["msg"=>"销售比例总和必须是100","state"=>2]);
            else
                $adddata["bilin"]=implode(',',$data["bilin"]);
            $adddata["yujijin"]=implode(',',$data["yujijin"]);
            //去年销售情况
            $adddata["lastyearp"]=implode(',',$data["lastyearp"]);
            $adddata["lastyearm"]=implode(',',$data["lastyearm"]);
            if($data["lastyearzong"])
                $adddata["lastyearzong"]=$data["lastyearzong"];
            else
                return json_encode(["msg"=>"经销商去年总销量必须填写","state"=>2]);
            if($data["lastyearno"])
                if($data["lastyearno"]>=1&&$data["lastyearno"]<=100)
                    $adddata["lastyearno"]=$data["lastyearno"];
                else
                   return json_encode(["msg"=>"在当地同品类经销商中的排行名次必须在1~100中","state"=>2]);  
            else
                return json_encode(["msg"=>"在当地同品类经销商中的排行名次必须填写","state"=>2]);
            //当地影响力
            $adddata["power"]=$data["power"];
            //价格掌控力
            $adddata["zhangkong"]=$data["zhangkong"];
            //信誉度
            $adddata["xinyu"]=$data["xinyu"];
            //流动资金总额
            if($data["liudong"])
                $adddata["liudong"]=$data["liudong"];
            //流动资金负债总额
            if($data["liudongfu"])
                $adddata["liudongfu"]=$data["liudongfu"];
            //应收账款总额
            if($data["yingshou"])
                $adddata["yingshou"]=$data["yingshou"];
            //流动资产
            if($data["liudongz"])
                $adddata["liudongz"]=$data["liudongz"];
            //总资产
            if($data["zongzichan"])
                $adddata["zongzichan"]=$data["zongzichan"];
            //总负债
            if($data["zongfu"])
                $adddata["zongfu"]=$data["zongfu"];
            //保证金
            if($data["baozheng"])
                $adddata["baozheng"]=$data["baozheng"];
            //曾经是否合作
            $adddata["iscom"]=$data["iscom"];
            if($adddata["iscom"]==1){
                //前期合作如果选是内容为必填
                //前期合作区域
                if(trim($data["com_area"]))
                    $adddata["com_area"]=trim($data["com_area"]);
                else
                    return json_encode(["msg"=>"前期合作期间所辖的区域必须填写","state"=>2]);
                //前期合作时间
                if($data["com_start"])
                    $adddata["com_start"]=$data["com_start"];
                else
                    return json_encode(["msg"=>"前期合作时间必须填写","state"=>2]);
                if($data["com_end"])
                    $adddata["com_end"]=$data["com_end"];
                else
                    return json_encode(["msg"=>"前期合作时间必须填写","state"=>2]);
                //前期合作年均
                if($data["com_money"])
                    $adddata["com_money"]=$data["com_money"];
                else
                    return json_encode(["msg"=>"前期合作年均销售额必须填写","state"=>2]);
                //其他情况
                if(trim($data["com_other"]))
                    $adddata["com_other"]=trim($data["com_other"]);
                //终止原因
                if(trim($data["end_reson"]))
                    $adddata["end_reson"]=trim($data["end_reson"]);
                else
                    return json_encode(["msg"=>"前期合作终止原因必须填写","state"=>2]);
            }
            //是否专人
            $adddata["iszhuan"]=$data["iszhuan"];
            if($data["zhuan_man"])
                $adddata["zhuan_man"]=$data["zhuan_man"];
            if($data["zhuan_dai"])
                $adddata["zhuan_dai"]=$data["zhuan_dai"];
            if($data["zhuanche"])
                $adddata["zhuanche"]=$data["zhuanche"];
            if($data["hunche"])
                $adddata["hunche"]=$data["hunche"];
            //应到位资金
            if($data["daowei"])
                $adddata["daowei"]=$data["daowei"];
            else
                return json_encode(["msg"=>"应到位资金必须填写","state"=>2]);
            //首批回款
            if($data["shoupi"])
                $adddata["shoupi"]=$data["shoupi"];
            else
                return json_encode(["msg"=>"首批回款必须填写","state"=>2]);
            //仓库情况
            //仓库楼层
            $adddata["ku_ceng"]=$data["ku_ceng"];
            $adddata["ku_gao"]=$data["ku_gao"];
            $adddata["ku_mianji"]=$data["ku_mianji"];
            $adddata["ku_my_mianji"]=$data["ku_my_mianji"];
            //C类点sku
            $adddata["prosp"]=$data["prosp"];
            //预计设业代
            if($data["yujisheyedai"])
                $adddata["yujisheyedai"]=$data["yujisheyedai"];
            else
                return json_encode(["msg"=>"预计设业代必须填写","state"=>2]);
            //专营人
            if($data["zhuanyingren"])
                $adddata["zhuanyingren"]=$data["zhuanyingren"];
            else
                return json_encode(["msg"=>"专营人必须选择","state"=>2]);
            //导购
            if($data["zhuan_dg_dian"])
                $adddata["zhuan_dg_dian"]=$data["zhuan_dg_dian"];
            else
                $adddata["zhuan_dg_dian"]=0;
            if($data["zhuan_dg_ren"])
                $adddata["zhuan_dg_ren"]=$data["zhuan_dg_ren"];
            else
                $adddata["zhuan_dg_ren"]=0;
            if($data["jian_dg_dian"])
                $adddata["jian_dg_dian"]=$data["jian_dg_dian"];
            else
                $adddata["jian_dg_dian"]=0;
            if($data["jian_dg_ren"])
                $adddata["jian_dg_ren"]=$data["jian_dg_ren"];
            else
                $adddata["jian_dg_ren"]=0;
            //资信限额支持方式
            $adddata["zxfs"]=$data["zxfs"];
            //是否BDF
            $adddata["is_bdf"]=$data["is_bdf"];
            if($data["is_bdf"]==1){
                $adddata["xingyongedu"]=$data["xingyongedu"];
                $adddata["dgalv"]=$data["dgalv"];
            }
            //账期
            $adddata["iszhang"]=$data["iszhang"];
            if($data["iszhang"]==1){
                $adddata["zhangtian"]=$data["zhangtian"];
                $adddata["dgabi"]=$data["dgabi"];
            }
            //返利政策描述
            if(trim($data["miaoshu"]))
                $adddata["miaoshu"]=trim($data["miaoshu"]);
            //BDF品牌
            $tmpbdfpp=[];$tmpbdfpb=[];
            for($i=0;$i<count($data["bdfpro"]);$i++){
                if($data["bdfpro"][$i]){
                    if($data["bdfprobi"][$i]){
                        $tmpbdfpp[]=$data["bdfpro"][$i];
                        $tmpbdfpb[]=$data["bdfprobi"][$i];
                    }else{
                        return json_encode(["msg"=>"存在未设定对应百分比的BDF对应品牌","state"=>2]);
                    }
                }
            }
            if($tmpbdfpp){
                $adddata["bdfpp"]=implode(',',$tmpbdfpp);
                $adddata["bdfpb"]=implode(',',$tmpbdfpb);
            }
            
            //附件
            if($data["attach"])
                $adddata["fujian"]=$data["attach"];
            $adddata["state"]=$data["state"];
            //
        if($data["kid"]){
            //修改
        }else{
            //新增
            //生成单号
            $timenow=date("Ymd");
            $num=Db::table("jxs_kaihu")->where("no like '$timenow%'")->count();
            $num++;
            $strnum=$timenow.sprintf("%05d", $num);
            $adddata["no"]=$strnum;
            $adddata["cuser"]=Session::get("employee_id");
            $adddata["puser"]=Session::get("employee_id");
            $adddata["ctime"]=time();
            $adddata["ptime"]=time();
           // print_r($adddata);exit;
            try{
                $res1=Db::table("jxs_kaihu")->insert($adddata);
            }catch(\Exception $e){
                //return $e->getMessage();
                return json_encode(["msg"=>"系统繁忙请稍候","state"=>2]);
           
            }
            if($res1)
                return json_encode(["msg"=>"","state"=>1]);
            else
                return json_encode(["msg"=>"系统繁忙请稍候","state"=>2]);
        }
    }
}